package com.wdb.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wdb.srv.UserService;

/**
 * @author ld
 * @date 3, 11, 2015
 * @blog http://localhost:8080/WDB/login?username=?&password=?
 */
public class LoginServlet extends HttpServlet {
	
	private static final long serialVersionUID = -7715894432269979527L;
	private UserService us;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("LoginServlet 被创建！");
		super.destroy();
	}

	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("LoginServlet 被销毁！");
		super.init();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=UTF-8");
		String cop = request.getParameter("do");
		if(cop.equals("out")){
			request.getSession().removeAttribute("name");
			request.getSession().invalidate();
		}
	
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//response.setContentType("text/html;charset=UTF-8");
		String name = request.getParameter("username");
		System.out.println(name);
		String pwd = request.getParameter("password");
		System.out.println(pwd);
		try {
			us = new UserService();
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		request.getSession().setAttribute("name", name);
		
		try {
			if(us.doLogin(name, pwd).equals("success"))
			{
				request.getSession().setAttribute("uid",String.valueOf(us.getUserID(name,pwd)));
				response.sendRedirect("./home.jsp");
			}
			else{
				response.sendRedirect("./error.jsp");
			}
				
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.sendRedirect("./error.jsp");
		} 
		
		
	}
}
